<template>
  <div>
    <page-loading
      :loading.sync="pageLoading"
      :error.sync="pageError"
      :enable-pull-refresh="false"
      @reload="getData"
    >
      <template v-if="hasTopicInfo">
        <topic-info
          :topic-id="topicId"
          :title="topicInfo.tag_name"
          :view="view"
          :discuss="discuss"
          :active-users="activeUsers"
        />
        <topic-list
          :topic-name="name"
          :topic-id="topicId"
        />
      </template>
    </page-loading>
  </div>
</template>

<script>
import PageLoading from '@/components/page-loading/PageLoading.vue'
import TopicInfo from '@/components/topic/TopicInfo.vue'
import TopicList from '@/components/topic/TopicList.vue'
import pageLoadingMixin from '@/mixins/pageLoading.js'
import { apiGetInfo, apiGetActiveUsers } from '@/api/topic.js'
export default {
  name: 'Topic',
  mixins: [pageLoadingMixin],
  inject: ['rootThemeColor', 'rootTitle'],
  metaInfo () {
    return {
      title: this.title
    }
  },
  components: {
    PageLoading,
    TopicInfo,
    TopicList
  },
  props: {
    // 话题
    name: {
      type: String
    }
  },
  data () {
    return {
      topicId: null,
      topicInfo: null,
      view: 0,
      discuss: 0,
      activeUsers: []
    }
  },
  computed: {
    hasTopicInfo () {
      return this.topicInfo !== null
    },
    title () {
      return `话题-${this.name}_${this.rootTitle}`
    }
  },
  watch: {
    name (newVal) {
      this.resetData()
      this.getData()
    }
  },
  created () {
    this.getData()
  },
  methods: {
    resetData () {
      this.topicId = null
      this.topicInfo = null
      this.view = 0
      this.discuss = 0
      this.activeUsers = []
      this.pageLoading = true
      this.pageError = false
    },
    getData () {
      apiGetInfo({ tagName: this.name }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          this.topicId = data.tag_id
          this.topicInfo = data
          return data
        } else {
          this.pageError = true
        }
      }).then(res => {
        this.getActiveUsers()
      }).catch(err => {
        console.log(err)
        this.pageError = true
      }).finally(() => {
        this.pageLoading = false
      })
    },
    getActiveUsers () {
      apiGetActiveUsers({ topicId: this.topicId }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          this.view = data.view_count
          this.discuss = data.discuss_count
          this.activeUsers = data.active_users
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
